package personal.xjl._23java1studentdemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import personal.xjl._23java1studentdemo.mapper.TeacherMapper;
import personal.xjl._23java1studentdemo.model.Student;
import personal.xjl._23java1studentdemo.model.Teacher;
import personal.xjl._23java1studentdemo.service.TeacherService;

import java.util.List;

@Controller
@RequestMapping("/Teacher")
public class TeacherController {
    @Autowired
    TeacherService teacherService;
    TeacherMapper teacherMapper;
    @RequestMapping("list")
    public String list(Model model) {
        List<Teacher> teachers = teacherService.findAll();
        model.addAttribute("teachers", teachers);
        return "listTeachers";
    }
    @RequestMapping("remove")
    public String remove(int id) {
        teacherService.remove(id);
        return "redirect:/Teacher/list/1/3";
    }
    @RequestMapping("add")
    public String add(Teacher teacher) {
        teacherService.add(teacher);
        return "redirect:/Teacher/list/1/3";
    }
    @RequestMapping("toEdit")
    public String toEdit(int id, Model model) {
        Teacher oldTeacher=teacherService.findById(id);
        model.addAttribute("teacher", oldTeacher);
        return "editTeacher";
    }

    @RequestMapping("edit")
    public String edit(Teacher teacher) {
        teacherService.edit(teacher);
        return "redirect:/Teacher/list/1/3";
    }

    @RequestMapping("list/{currPage}/{pageSize}")
    //分页显示
    public String list(Model model, @PathVariable("currPage") int currPage, @PathVariable("pageSize")int pageSize){
        if(currPage<1) currPage=1;
        if (pageSize <=0) pageSize=5;
        List<Teacher> teachers = teacherService.findByPage(currPage, pageSize);
        model.addAttribute("teachers", teachers);
        return "listTeachers";
    }

    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    @GetMapping("/Teacher/list")
    public String listTeachers(Model model) {
        try {
            List<Teacher> teachers = teacherMapper.selectAll();
            logger.info("查询到的教师数量: {}", teachers.size());
            model.addAttribute("teachers", teachers);
            return "listTeachers";
        } catch (Exception e) {
            logger.error("查询教师信息时出错", e);
            throw e;
        }
    }
}
